// service-worker.js
self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open('turbo-warp-cloud-list-v1').then((cache) => {
            return cache.addAll([
                '/',
                '/index.html'
            ]);
        })
    );
});

self.addEventListener('fetch', (event) => {
    // 处理API请求
    if (event.request.url.includes('/api/')) {
        event.respondWith(handleAPIRequest(event.request));
        return;
    }
    
    // 处理其他请求
    event.respondWith(
        caches.match(event.request).then((response) => {
            return response || fetch(event.request);
        })
    );
});

// 从IndexedDB获取数据
function getData() {
    return new Promise((resolve) => {
        const request = indexedDB.open('TurboWarpCloudList', 1);
        
        request.onupgradeneeded = (event) => {
            const db = event.target.result;
            if (!db.objectStoreNames.contains('cloudData')) {
                db.createObjectStore('cloudData', { keyPath: 'id' });
            }
        };
        
        request.onsuccess = (event) => {
            const db = event.target.result;
            const transaction = db.transaction('cloudData', 'readonly');
            const store = transaction.objectStore('cloudData');
            const getRequest = store.get('data');
            
            getRequest.onsuccess = () => {
                resolve(getRequest.result ? getRequest.result.value : {});
            };
            
            getRequest.onerror = () => {
                resolve({});
            };
        };
        
        request.onerror = () => {
            resolve({});
        };
    });
}

// 保存数据到IndexedDB
function saveData(data) {
    return new Promise((resolve) => {
        const request = indexedDB.open('TurboWarpCloudList', 1);
        
        request.onupgradeneeded = (event) => {
            const db = event.target.result;
            if (!db.objectStoreNames.contains('cloudData')) {
                db.createObjectStore('cloudData', { keyPath: 'id' });
            }
        };
        
        request.onsuccess = (event) => {
            const db = event.target.result;
            const transaction = db.transaction('cloudData', 'readwrite');
            const store = transaction.objectStore('cloudData');
            
            store.put({ id: 'data', value: data });
            
            transaction.oncomplete = () => {
                resolve();
            };
        };
    });
}

// 处理API请求
async function handleAPIRequest(request) {
    try {
        const url = new URL(request.url);
        const path = url.pathname;
        let cloudData = await getData();
        
        // 处理OPTIONS请求（跨域预检）
        if (request.method === 'OPTIONS') {
            return new Response(null, {
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
                    'Access-Control-Allow-Headers': 'Content-Type'
                }
            });
        }
        
        // 解析请求数据
        let requestData = {};
        if (request.method === 'POST') {
            try {
                requestData = await request.json();
            } catch (e) {
                // 尝试解析表单数据
                const formData = await request.formData();
                formData.forEach((value, key) => {
                    requestData[key] = value;
                });
            }
        }
        
        // 处理不同的API端点
        let responseData = {};
        
        // 测试连接
        if (path === '/api/ping') {
            responseData = {
                success: true,
                message: "连接成功",
                serverTime: Date.now()
            };
        }
        
        // 保存列表
        else if (path === '/api/save' && request.method === 'POST') {
            const { projectId, listName, items } = requestData;
            
            if (!projectId || !listName || !Array.isArray(items)) {
                responseData = { success: false, message: "参数错误" };
            } else {
                if (!cloudData[projectId]) cloudData[projectId] = {};
                cloudData[projectId][listName] = {
                    items: [...items],
                    timestamp: Date.now()
                };
                
                await saveData(cloudData);
                responseData = { success: true, message: "列表保存成功" };
            }
        }
        
        // 加载列表
        else if (path === '/api/load' && request.method === 'GET') {
            const projectId = url.searchParams.get('projectId');
            const listName = url.searchParams.get('listName');
            
            if (!projectId || !listName) {
                responseData = { success: false, message: "参数错误" };
            } else {
                const list = cloudData[projectId]?.[listName];
                if (!list) {
                    responseData = { success: false, message: "列表不存在" };
                } else {
                    responseData = { success: true, items: list.items };
                }
            }
        }
        
        // 添加列表项
        else if (path === '/api/add' && request.method === 'POST') {
            const { projectId, listName, item } = requestData;
            
            if (!projectId || !listName || item === undefined) {
                responseData = { success: false, message: "参数错误" };
            } else {
                if (!cloudData[projectId]) cloudData[projectId] = {};
                if (!cloudData[projectId][listName]) {
                    cloudData[projectId][listName] = { items: [], timestamp: Date.now() };
                }
                
                cloudData[projectId][listName].items.push(item);
                cloudData[projectId][listName].timestamp = Date.now();
                
                await saveData(cloudData);
                responseData = {
                    success: true,
                    message: "项已添加",
                    newLength: cloudData[projectId][listName].items.length
                };
            }
        }
        
        // 删除列表项
        else if (path === '/api/remove' && request.method === 'POST') {
            const { projectId, listName, index } = requestData;
            
            if (!projectId || !listName || index === undefined) {
                responseData = { success: false, message: "参数错误" };
            } else {
                const list = cloudData[projectId]?.[listName];
                if (!list || index < 0 || index >= list.items.length) {
                    responseData = { success: false, message: "索引无效" };
                } else {
                    list.items.splice(index, 1);
                    list.timestamp = Date.now();
                    
                    await saveData(cloudData);
                    responseData = {
                        success: true,
                        message: "项已删除",
                        newLength: list.items.length
                    };
                }
            }
        }
        
        // 未知API端点
        else {
            responseData = { success: false, message: "API端点不存在" };
        }
        
        // 返回响应
        return new Response(JSON.stringify(responseData), {
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*'
            }
        });
    } catch (error) {
        console.error('API请求处理错误:', error);
        return new Response(JSON.stringify({
            success: false,
            message: "服务器错误"
        }), {
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*'
            }
        });
    }
}
    